package com.cheer.ba.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.app.oss.UploadPicManager;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.utils.CacheUtils;
import com.cheer.ba.utils.IDCardValidate;
import com.cheer.ba.utils.ImageUtils;
import com.cheer.ba.utils.LogUtils;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.widget.ShowPopupView;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 办理油卡
 *
 * @author HQ
 *         created at 2017/5/13 0013 15:32
 */
public class HandleOilCardAty extends BaseCommAty implements ShowPopupView.OnItemPopupClick {

    @BindView(R.id.id_oil_root)
    LinearLayout mLinearRoot;

    //卡数量
    @BindView(R.id.id_oil_card_num_edit)
    EditText mEditCardNum;
    private String mCardNum;

    //真实姓名
    @BindView(R.id.id_oil_true_name_edit)
    EditText mEditTrueName;
    private String mSaveTrueName;
    //手机号
    @BindView(R.id.id_oil_phone_edit)
    EditText mEditPhone;
    private String mSavePhone;
    //邮寄地址
    @BindView(R.id.id_email_address_txt)
    TextView mTxtEmailAddress;
    private String mSaveHeadAddress;
    //详细地址
    @BindView(R.id.id_email_detail_address_edit)
    EditText mEditDeailAddress;
    private String mSaveDetailAddress;
    //身份证号
    @BindView(R.id.id_oil_idcard_edit)
    EditText mEditIdCardNum;
    private String mSaveIdCardNum;
    //身份证正面
    @BindView(R.id.id_idcard_1_img)
    ImageView mImgIdCard1;
    private String mSaveFacePath;
    //身份证反面
    @BindView(R.id.id_idcard_2_img)
    ImageView mImgIdCard2;
    private String mSaveConPath;

    //记录拍照 0 拍照 1 相册
    private int mRecordIndex;
    //记录相片的绝对路径
    private String mPhotoFileName;
    private File mPhotoFile;

    //弹出头像框
    private ShowPopupView popupView;
    public static final String[] POPUP_ITEMS = {"拍摄", "从相册上传"};

    //记录身份证正面还是反面  1 正面 2 反面
    private int mRecordPath;

    private static final char kongge = ' ';

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //身份证图片上传成功
                case 1:
                    ((OilMealPresenter) presenter).AskMyOilCards((mSaveHeadAddress + "|" + mSaveDetailAddress), mSaveIdCardNum.replaceAll(" ", "").trim(), "", mSavePhone, "1", mSaveTrueName, mSaveFacePath, mSaveConPath, mCardNum);
                    break;
            }
        }
    };

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_handle_oil_card, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new OilMealPresenter();
        ((OilMealPresenter) presenter).setmUpLoadPicManager();
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.handle_oil_card));
        setTitleRight("申请须知", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showActivity(aty, AskOilCardAty.class);
            }
        });
        popupView = new ShowPopupView(this);
        popupView.setOnItemPopupClick(this);
        mImgIdCard1.setImageResource(R.drawable.ic_idcard_face);
        mImgIdCard2.setImageResource(R.drawable.ic_idcard_con);
        mCardNum = "1";
        mEditCardNum.setText(mCardNum);
    }

    @Override
    public void initData() {
//        mEditIdCardNum.addTextChangedListener(new TextWatcher() {
//            // 改变之前text长度
//            int beforeTextLength = 0;
//            // 改变之前的文字
//            private CharSequence beforeChar;
//            // 改变之后text长度
//            int onTextLength = 0;
//            // 是否改变空格或光标
//            boolean isChanged = false;
//            // 记录光标的位置
//            int location = 0;
//            private char[] tempChar;
//            private StringBuffer buffer = new StringBuffer();
//            // 已有空格数量
//            int konggeNumberB = 0;
//
//            @Override
//            public void onTextChanged(CharSequence s, int arg1, int arg2,
//                                      int arg3) {
//                onTextLength = s.length();
//                buffer.append(s.toString());
//                if (onTextLength == beforeTextLength || onTextLength <= 3
//                        || isChanged) {
//                    isChanged = false;
//                    return;
//                }
//                isChanged = true;
//            }
//
//            @Override
//            public void beforeTextChanged(CharSequence s, int arg1, int arg2,
//                                          int arg3) {
//                beforeTextLength = s.length();
//                if (buffer.length() > 0) {
//                    buffer.delete(0, buffer.length());
//                }
//                konggeNumberB = 0;
//                for (int i = 0; i < s.length(); i++) {
//                    if (s.charAt(i) == ' ') {
//                        konggeNumberB++;
//                    }
//                }
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                if (isChanged) {
//                    location = mEditIdCardNum.getSelectionEnd();
//                    int index = 0;
//                    while (index < buffer.length()) {
//                        if (buffer.charAt(index) == kongge) {
//                            buffer.deleteCharAt(index);
//                        } else {
//                            index++;
//                        }
//                    }
//                    index = 0;
//                    int konggeNumberC = 0;
//                    while (index < buffer.length()) {
//                        if ((index - 4) % 5 == 0) {
//                            buffer.insert(index, kongge);
//                            konggeNumberC++;
//                        }
//                        index++;
//                    }
//
//                    if (konggeNumberC > konggeNumberB) {
//                        location += (konggeNumberC - konggeNumberB);
//                    }
//
//                    tempChar = new char[buffer.length()];
//                    buffer.getChars(0, buffer.length(), tempChar, 0);
//                    String str = buffer.toString();
//                    if (location > str.length()) {
//                        location = str.length();
//                    } else if (location < 0) {
//                        location = 0;
//                    }
//                    mEditIdCardNum.setText(str);
//                    Editable etable = mEditIdCardNum.getText();
//                    Selection.setSelection(etable, location);
//                    isChanged = false;
//                }
//            }
//        });
    }

    private void handler() {
        getInputData();
        if (StringUtils.isEmpty(mCardNum)) {
            SVProgressHUD.showInfoWithStatus(aty, "请输入需要办理卡的数量");
        } else {
            int i = Integer.parseInt(mCardNum);
            if (i <= 0) {
                SVProgressHUD.showInfoWithStatus(aty, "办理卡数量要大于0");
            } else {
                if (i > 200) {
                    SVProgressHUD.showInfoWithStatus(aty, "办卡数量审批上限小于200张");
                } else {
                    if (StringUtils.isEmpty(mSaveTrueName)) {
                        SVProgressHUD.showInfoWithStatus(aty, "请输入您的真实姓名");
                    } else if (StringUtils.isEmpty(mSavePhone) || !StringUtils.isMobile(mSavePhone)) {
                        SVProgressHUD.showInfoWithStatus(aty, "请输入您的手机号");
                    } else if (StringUtils.isEmpty(mSaveHeadAddress)) {
                        SVProgressHUD.showInfoWithStatus(aty, "请选择您的邮寄地址");
                    } else if (StringUtils.isEmpty(mSaveDetailAddress)) {
                        SVProgressHUD.showInfoWithStatus(aty, "请填写您的详细地址");
                    } else if (StringUtils.isEmpty(mSaveIdCardNum)) {
                        SVProgressHUD.showInfoWithStatus(aty, "请输入正确的身份证号");
                    } else {
                        try {
                            String msg = IDCardValidate.IDCardValidate(mSaveIdCardNum);
                            if (StringUtils.isEmpty(msg)) {
                                if (StringUtils.isEmpty(mSaveFacePath)) {
                                    SVProgressHUD.showInfoWithStatus(aty, "请上传您的身份证正面照");
                                } else if (StringUtils.isEmpty(mSaveConPath)) {
                                    SVProgressHUD.showInfoWithStatus(aty, "请上传您的身份证反面照");
                                } else {
//            ((OilMealPresenter) presenter).initNews((mSaveHeadAddress + "|" + mSaveDetailAddress), mSaveIdCardNum, mSavePhone, mSaveTrueName);
                                    ((OilMealPresenter) presenter).getMyOilCards(true, "0", "", "", "", "", "");
                                }
                            } else {
                                SVProgressHUD.showInfoWithStatus(aty, msg);
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    public void getInputData() {
        mCardNum = mEditCardNum.getText().toString().trim();
        mSaveTrueName = mEditTrueName.getText().toString().trim();
        mSavePhone = mEditPhone.getText().toString().trim();
        mSaveDetailAddress = mEditDeailAddress.getText().toString().trim();
        mSaveIdCardNum = mEditIdCardNum.getText().toString().trim();
    }


    @OnClick({R.id.id_email_linear, R.id.id_idcard_1_img, R.id.id_idcard_2_img, R.id.id_handle_oil_btn})
    public void onClick(View mView) {
        switch (mView.getId()) {
            //选择邮寄地址
            case R.id.id_email_linear:
                Intent email = new Intent(aty, ProvinceAreaAty.class);
                startActivityForResult(email, IntentCode.Area.PROVINCE_REQUEST_CODE);
                break;
            //身份证正面
            case R.id.id_idcard_1_img:
                mRecordPath = 1;
                popupView.showAtLocPop(mLinearRoot, POPUP_ITEMS);
                break;
            //身份证反面
            case R.id.id_idcard_2_img:
                mRecordPath = 2;
                popupView.showAtLocPop(mLinearRoot, POPUP_ITEMS);
                break;
            case R.id.id_handle_oil_btn:
                //提交按钮
                handler();
                break;
        }
    }


    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.MY_OIL_CARDS)) {
                //该用户有油卡,要收手续费
                List<String> mPaths = new ArrayList<String>();
                mPaths.add(mSaveFacePath);
                mPaths.add(mSaveConPath);
                ((OilMealPresenter) presenter).uploadPic(mPaths, null);
            } else if (TextUtils.equals(tag, ConstantTag.DATA_SUCCESS_NULL)) {
                //该用户没有油卡
                List<String> mPaths = new ArrayList<String>();
                mPaths.add(mSaveFacePath);
                mPaths.add(mSaveConPath);

                ((OilMealPresenter) presenter).uploadPic(mPaths, null);
            } else if (TextUtils.equals(tag, ConstantTag.HEADPIC_UP_SUCCESS)) {
                //图片上传成功
                List<UploadPicManager.UploadInfo> resultList = (List<UploadPicManager.UploadInfo>) t;
                mSaveFacePath = resultList.get(0).fileSavePath;
                mSaveConPath = resultList.get(1).fileSavePath;
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            } else if (TextUtils.equals(tag, ConstantTag.HEADPIC_UP_FAIL)) {
                //图片上传失败
                LogUtils.LogD("图片上传失败", "图片上传失败");
                SVProgressHUD.showInfoWithStatus(aty, "身份证照片上传失败,请检查网络");
            } else if (TextUtils.equals(tag, ConstantTag.ASK_OIL_CARD_SUCCESS)) {
                //申请油卡成功
                SVProgressHUD.showSuccessWithStatus(aty, "申请成功");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
            }
        }
    }

    /**
     * 添加身份证照片
     */
    @Override
    public void OnItemClick(int position, String tag) {
        switch (position) {
            //拍照
            case 0:
                mRecordIndex = 0;
                checkPermissCamer();
                break;
            //系统相册
            case 1:
                mRecordIndex = 1;
                checkPermissCamer();
                break;
        }
    }

    /**
     * 检测用户是否开启权限
     */
    private void checkPermissCamer() {
        String[] perms = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//        if (mRecordIndex == 0) {
//            //拍照
//            perms = new String[]{Manifest.permission.CAMERA};
//        } else {
//            //系统相册
//            perms = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//        }
        if (!mayRequestPermission(perms)) {
            return;
        }
        toPhotoGraph();
    }

    @Override
    public void requestPermissionResult(boolean allowPermission) {
        if (allowPermission) {
            toPhotoGraph();
        }
    }

    /**
     * 处理拍照，系统相册
     */
    private void toPhotoGraph() {
        if (mRecordIndex == 0) {
            //拍照
            // 应该先判断SD卡是否存在
            String SDState = Environment.getExternalStorageState();
            if (SDState.equals(Environment.MEDIA_MOUNTED)) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                initHeadPicPath();
                // 下面这句指定调用相机拍照后的照片存储的路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));
                startActivityForResult(intent, IntentCode.General.REQUEST_CODE_TAKE_PICTURE);// 使用手机进行拍照的请求码是：1
            } else {
                SVProgressHUD.showInfoWithStatus(aty, getString(R.string.personal_no_sd_card));
            }
        } else {
            //相册
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            /**
             * 下面这句话，与其它方式写是一样的效果，如果：
             * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
             * intent.setType(""image/*");设置数据类型
             * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
             */
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    "image/*");
            startActivityForResult(intent, IntentCode.General.REQUEST_CODE_TAKE_ALBUM);// 从相册中取图片的请求码是：2
        }
    }

    private void initHeadPicPath() {
        // 创建拍摄照片保存的文件夹及图片文件名
        String imgName = StringUtils.getPhotoFileName();
        File f = new File(CacheUtils.getCacheDirectory(aty, true, "pic") + imgName);
        if (f.exists()) {
            f.delete();
        }
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (f != null) {
            if (mRecordPath == 1) {
                mSaveFacePath = f.getAbsolutePath();
            } else {
                mSaveConPath = f.getAbsolutePath();
            }
            mPhotoFileName = f.getAbsolutePath();
        }
        mPhotoFile = f;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                // 已经选择了照片，这个是通过手机相机拍照返回的请求码
                case IntentCode.General.REQUEST_CODE_TAKE_PICTURE:
                    if (!TextUtils.isEmpty(mPhotoFileName)) {
                        setHeadImage(mPhotoFileName);
                    }
                    break;
                // 相册请求码
                case IntentCode.General.REQUEST_CODE_TAKE_ALBUM:
                    if (null != data) {
                        String path = ImageUtils.getAlbum(aty, data);
                        if (!StringUtils.isEmpty(path)) {
                            setHeadImage(path);
                        } else {
                            SVProgressHUD.showInfoWithStatus(aty, "图片路径错误");
                        }
                    }
                    break;
            }
        }
        if (requestCode == IntentCode.Area.PROVINCE_REQUEST_CODE) {
            if (resultCode == IntentCode.Area.PROVINCE_RESULT_CODE) {
                if (null != data) {
                    mSaveHeadAddress = data.getStringExtra(IntentKey.General.KEY_DATA);
                    mTxtEmailAddress.setText(mSaveHeadAddress);
                    Session.setUser_area(mSaveHeadAddress);
                    String[] s = StringUtils.strSplit(mSaveHeadAddress);
                    mSaveHeadAddress = s[0] + "|" + s[1] + "|" + s[2];
                }
            }
        }
    }

    /**
     * oss上传图片
     *
     * @param filePath
     */
    public void setHeadImage(String filePath) {
//        ((PersonalPresenter) presenter).uploadPic(filePath, mUserHeadImg);
        LogUtils.LogD("headImg", filePath + "---------");
//        Bitmap bitmap = null;
//        try {
//            bitmap = ImageUtils.autoResizeFromLocalFile(filePath, mImgIdCard1);
        if (mRecordPath == 1) {
//                mSaveFacePath = ImageUtils.saveBitmap(aty, bitmap);
            mSaveFacePath = filePath;
            ImageUtils.showImg(aty, mSaveFacePath, R.drawable.ic_idcard_face, R.drawable.ic_idcard_face, mImgIdCard1);
        } else if (mRecordPath == 2) {
//                mSaveConPath = ImageUtils.saveBitmap(aty, bitmap);
            mSaveConPath = filePath;
            ImageUtils.showImg(aty, mSaveConPath, R.drawable.ic_idcard_con, R.drawable.ic_idcard_con, mImgIdCard2);
        }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.LogD("handle", "----------");
    }


}
